<?php

/**
 * Make input hidden element to detect page id
 * @param $id
 * @return string
 */
function page_id($id)
{
    return "<input type=\"hidden\" id=\"js-page-id\" value=\"$id\" />";
}

/**
 * Get or set URL will be redirect after login success (give empty parameters to get)
 * @param null $url
 * @return null
 */
function pre_login_url($url = null)
{
    if ($url === null) {
        $url = Session::get(PRE_LOGIN_URL_SESSION, '/');
        Session::forget(PRE_LOGIN_URL_SESSION);
    } else {
        Session::put(PRE_LOGIN_URL_SESSION, $url);
    }

    return $url;
}

/**
 * Just a Shared::make_message wrapper
 * @param $params
 * @return Laravel\View
 */
function message_page($params)
{
    return Shared::make_message($params);
}

/**
 * Just a Shared::make_message wrapper for error messaging
 * @param $content
 * @param string $title
 * @param string $redirect_url
 * @param int $redirect_timeout
 * @param string $redirect_message
 * @return Laravel\View
 */
function error($content, $title = 'Xảy ra lỗi', $redirect_url = '/', $redirect_timeout = 5,
               $redirect_message = 'Đang chuyển đến trang yêu cầu')
{
    $type = 'error';
    return Shared::make_message(compact('content', 'title',
        'redirect_url', 'redirect_timeout', 'redirect_message', 'type'));
}

function message($content, $title, $redirect_url = '/', $redirect_timeout = 5,
                 $redirect_message = 'Đang chuyển đến trang yêu cầu')
{
    return Shared::make_message(compact('content', 'title', 'redirect_url', 'redirect_timeout', 'redirect_message'));
}

function confirm($content, $title, $confirm_submit_url, $confirm_cancel_url = '/',
                 $confirm_submit_label = 'Đồng ý', $confirm_cancel_label = 'Hủy bỏ')
{
    $type = 'warning';
    return Shared::make_message(compact('content', 'title', 'confirm_submit_url', 'confirm_cancel_url',
        'confirm_submit_label', 'confirm_cancel_label', 'type'
    ));
}

function get_random_rss_news($quantity = 10)
{
    $txt = File::get(path('storage') . 'cache/rss/' . Config::get('application.rss'));
    $data = json_decode($txt);
    $len = count($data);
    $result = array();
    if ($quantity === 0) return $data;

    if ($len < $quantity) {
        throw new Exception('Số lượng tin yêu cầu quá lớn!');
    }

    $track = array_fill(0, $len, false);
    for ($i = 0; $i < $quantity; $i++) {
        do {
            $rnd = rand(0, $len - 1);
        } while ($track[$rnd]);
        $result[] = $data[$rnd];
    }

    return $result;
}

function filter_rss($item) {

    // Remove extra A tag in description
    $pattern = '#<a.*?><img\s+src="(.*?)"/?></a>(.*?)($|<br)#i';
    $article = array(
        'link' => (string)$item->link,
        'title' => (string)$item->title,
    );
    if (preg_match($pattern, (string)$item->description, $matches)) {
        $article['thumbnail'] = $matches[1];
        $article['description'] = $matches[2];
    } else {
        return null;
    }


    return $article;
}


/**
 * Gửi email
 * @param $mail array
 *      + to_address
 *      + to_name
 *      + body
 *      + plain (options)
 *      + subject (options)
 * @return int
 * @throws Exception
 */
function send_mail($mail)
{
    \Laravel\Bundle::start('swiftmailer');
    $defaults = array(
        'plain' => 'Vui long xem o che do HTML (Vui lòng xem ở chế độ HTML)',
        'subject' => 'NhatroCT - Hỗ trợ',
        'username' => Config::get('mail.username'),
        'password' => Config::get('mail.password'),
        'from_address' => Config::get('mail.from_address'),
        'from_name' => Config::get('mail.from_name'),
    );

    $op = (object)array_merge($defaults, $mail);

    if (!isset($op->to_address) || !isset($op->to_name) || !isset($op->body)) {
        throw new Exception('Can not send email, without to_address or to_name or body field!');
    }

    #$mailer = IoC::resolve('mailer');

    $transporter = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
        ->setUsername($op->username)
        ->setPassword($op->password);

    $mailer = Swift_Mailer::newInstance($transporter);


    // Construct the message
    $message = Swift_Message::newInstance($op->subject)
        ->setFrom(array($op->from_address => $op->from_name))
        ->setTo(array($op->to_address => $op->to_name))
        ->addPart($op->plain, 'text/plain')
        ->setBody($op->body, 'text/html');

    $sent = $mailer->send($message);
    return $sent;
}

/** Chuyển đổi tiếng việt có dấu thành không dấu, thay thế các ký tự đặc (space -> -, etc)
 * @param $str
 * @return mixed
 */
function slug($str)
{
    $signed = array("à","á","ạ","ả","ã","â","ầ","ấ","ậ","ẩ","ẫ","ă","ằ","ắ"
    ,"ặ","ẳ","ẵ","è","é","ẹ","ẻ","ẽ","ê","ề","ế","ệ","ể","ễ","ì","í","ị","ỉ","ĩ",
        "ò","ó","ọ","ỏ","õ","ô","ồ","ố","ộ","ổ","ỗ","ơ"
    ,"ờ","ớ","ợ","ở","ỡ",
        "ù","ú","ụ","ủ","ũ","ư","ừ","ứ","ự","ử","ữ",
        "ỳ","ý","ỵ","ỷ","ỹ",
        "đ",
        "À","Á","Ạ","Ả","Ã","Â","Ầ","Ấ","Ậ","Ẩ","Ẫ","Ă"
    ,"Ằ","Ắ","Ặ","Ẳ","Ẵ",
        "È","É","Ẹ","Ẻ","Ẽ","Ê","Ề","Ế","Ệ","Ể","Ễ",
        "Ì","Í","Ị","Ỉ","Ĩ",
        "Ò","Ó","Ọ","Ỏ","Õ","Ô","Ồ","Ố","Ộ","Ổ","Ỗ","Ơ"
    ,"Ờ","Ớ","Ợ","Ở","Ỡ",
        "Ù","Ú","Ụ","Ủ","Ũ","Ư","Ừ","Ứ","Ự","Ử","Ữ",
        "Ỳ","Ý","Ỵ","Ỷ","Ỹ",
        "Đ","ê","ù","à");

    $unsigned = array("a","a","a","a","a","a","a","a","a","a","a"
    ,"a","a","a","a","a","a",
        "e","e","e","e","e","e","e","e","e","e","e",
        "i","i","i","i","i",
        "o","o","o","o","o","o","o","o","o","o","o","o"
    ,"o","o","o","o","o",
        "u","u","u","u","u","u","u","u","u","u","u",
        "y","y","y","y","y",
        "d",
        "A","A","A","A","A","A","A","A","A","A","A","A"
    ,"A","A","A","A","A",
        "E","E","E","E","E","E","E","E","E","E","E",
        "I","I","I","I","I",
        "O","O","O","O","O","O","O","O","O","O","O","O"
    ,"O","O","O","O","O",
        "U","U","U","U","U","U","U","U","U","U","U",
        "Y","Y","Y","Y","Y",
        "D","e","u","a");
    $text = str_replace($signed, $unsigned, $str);

    $replacements = array(
        ' ' => '-',
        ',' => '',
        '[' => '-',
        ']' => '-'
    );
    // remove space
    foreach ($replacements as $pattern => $rep) {
        $text = str_replace($pattern, $rep, $text);
    }

    return $text;
}

function is_not_null($var)
{
    return !is_null($var);
}

/**
 * Just alias for Setting::get & Setting::set method
 * @param $s_key
 * @param null $value
 * @param null $description
 * @return null|mixed
 */
function setting($s_key, $value = null, $description = null)
{
    // Set
    if (is_not_null($value)) {
        return Setting::set($s_key, $value, $description);
    } else {
        return Setting::get($s_key);
    }
}

function dup_str($str, $count)
{
    $result = '';
    for ($i = 0; $i < $count; $i++) {
        $result .= $str;
    }

    return $result;
}


function space($count = 1)
{
    return dup_str(' ', $count);
}

function format_vnd($num)
{
    return number_format(round($num, 1) * 1000, 0, '.', ',') . ' VNĐ';

}